package com.ocom.wxapi.config.interceptor;

import com.ocom.common.utils.IPUtils;
import com.ocom.common.utils.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.naming.AuthenticationNotSupportedException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器 验证token中的ip
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String auth = request.getHeader("Authorization");

        if(auth==null || StringUtil.isEmpty(auth)){
       //     throw new AuthenticationNotSupportedException();
        }

        String nowIp= IPUtils.getHostIp();
        /**

        Map<String,Object> tokenParse= SecurityUtils.getTokenParse();


        String ip =String.valueOf(tokenParse.get("ip"));
        String client_id =String.valueOf(tokenParse.get("client_id"));

        PrintWriter out = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        //非分布式 仅微信使用token
//        if(!client_id.equals("client_2")){
//            PrintWriter out = response.getWriter();
//            out.append((CharSequence) ResultUtil.error(ResultEnum.Err_204));
//            return false;
//        }

        //token ip不一致
        if(!nowIp.equals(ip)){
            JSONObject res = new JSONObject();
            res.put("code", 401);
            res.put("msg", "非法Ip");
            res.put("data", "");
            out = response.getWriter();
            out.append(res.toString());
            return false;
        }

         **/
        return true;


        //验证ip
        /**

        if (request.getParameter("machNo") == null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                JSONObject res = new JSONObject();
                res.put("result", false);
                res.put("msg", "验签失败");
                out = response.getWriter();
                out.append(res.toString());
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
        }
        **/



    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }


}